package com.rsy.product.Web;

import com.rsy.product.entity.CategoryEntity;
import com.rsy.product.service.CategoryService;
import com.rsy.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 前端页面默认地址  分类展示
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //查村出所有的一级分类
        List<CategoryEntity> catagories = categoryService.getLevel1Catagories();
        model.addAttribute("catagories", catagories);

        //classpath:/templates/
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String,List<Catelog2Vo>> getCatelogJson(){
        Map<String,List<Catelog2Vo>>  catelogJson = categoryService.getCatelogJson();
        return catelogJson;
    }

    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        //1.获取一把锁，只要名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("lock");
        //2.加锁和解锁
        //解决了锁的自动续期，如果业务超长，会自动给锁续上新的30秒，
        //加锁的业务只要运行完成，就不会给当前的锁续期，即使不手动释放，也会在30秒后自动删除
        lock.lock();//阻塞式等待，默认jade锁就是30秒时间
        try {
            System.out.println("加锁成功，执行业务方法..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e){

        }finally {
            lock.unlock();
            System.out.println("释放锁..."+Thread.currentThread().getId());
        }
        return "hello";
    }

    @PostMapping("/test")
    public String Test(@RequestBody Test1 test1){
        return null;
    }

}
